package cc.shacocloud.kotlin.tools.jdbc.impl

import cc.shacocloud.kotlin.tools.jdbc.JdbcUtil.getResultSetValue
import cc.shacocloud.kotlin.tools.jdbc.JdbcUtil.lookupColumnName
import cc.shacocloud.kotlin.tools.jdbc.RowMapper
import java.sql.ResultSet

/**
 * 创建基于map的 [RowMapper]
 */
open class ColumnMapRowMapper : RowMapper<Map<String, Any?>> {

    override fun mapRow(rs: ResultSet, rowNum: Int): Map<String, Any?> {
        val rsmd = rs.metaData
        val columnCount = rsmd.columnCount
        val mapOfColumnValues = createColumnMap(columnCount)
        for (i in 1..columnCount) {
            val column = rsmd.lookupColumnName(i)
            mapOfColumnValues.putIfAbsent(getColumnKey(column), getColumnValue(rs, i))
        }
        return mapOfColumnValues
    }

    open fun createColumnMap(columnCount: Int): MutableMap<String, Any?> {
        return mutableMapOf()
    }

    open fun getColumnKey(columnName: String): String {
        return columnName
    }

    /**
     * 检索指定列的 JDBC 对象值
     */
    open fun getColumnValue(rs: ResultSet, index: Int): Any? {
        return rs.getResultSetValue(index)
    }
}
